package user_role_service

import (
	"gorm.io/gorm"
	ud "pear-admin-layui-go/app/sys/user/domain"
	urd "pear-admin-layui-go/app/sys/user_role/domain"
	fd "pear-admin-layui-go/framework/database"
)

func UserRoleEdit(urer *ud.UserRoleEditRquest) *gorm.DB {
	if urer.Checked {
		// 插入
		return fd.Db.Create(&urd.UserRole{
			UserId:     urer.Id,
			RoleId:     urer.RoleId,
			CreateTime: urer.UpdateTime,
			CreateName: urer.UpdateName,
			CreateBy:   urer.UpdateBy,
		})
	} else {
		// 删除
		return fd.Db.Where("user_id = ? AND role_id = ?", urer.Id, urer.RoleId).Delete(&urd.UserRole{})
	}
}

func UserRoleSave(userRoles []urd.UserRole) (int, int) {
	count := len(userRoles)
	success := 0
	for _, v := range userRoles {
		tx := fd.Db.Create(&v)
		success += int(tx.RowsAffected)
	}
	return success, count
}
